import axios from "axios";
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Input, Form, Notify } from "react-vant";
import { useAppDispatch } from "../../app/hooks";
import { loginSuccess } from "../../app/user/userSlice";

export default () => {
  const [form] = Form.useForm();
  const [count, setCount] = useState(5);
  const [code, setCode] = useState("");
  const dispatch = useAppDispatch();
	const navigate = useNavigate()
  const onFinish = async (values) => {
    if (values.code !== code) {
      Notify.show({ type: "warning", message: "验证码错误！" });
      return;
    }
    const resp = await axios.post("/api/login", values);
    const { code: myCode, data, message } = resp.data;

    if (myCode === 200) {
      dispatch(loginSuccess(data));
      Notify.show({ type: "primary", message });
			navigate(-1)
    } else {
      Notify.show({ type: "danger", message });
    }
  };

  const getCode = () => {
    const timer = setInterval(() => {
      setCount((state) => {
        // 写成函数 可以保证每一次获取state的值 都是上一次的结果
        if (state <= 1) {
          clearInterval(timer);
          setCount(5);
        }
        return state - 1;
      });
    }, 1000);
    const code = Math.random().toString(36).slice(2, 6);
    console.log(code);
    setCode(code);
  };

  return (
    <div>
      <Form
        form={form}
        onFinish={onFinish}
        footer={
          <div style={{ margin: "16px 16px 0" }}>
            <Button round nativeType="submit" type="primary" block>
              登录
            </Button>
          </div>
        }
      >
        <Form.Item
          rules={[{ required: true, message: "请填写手机号" }]}
          name="tel"
          label="手机号"
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item
          rules={[{ required: true, message: "请填写密码" }]}
          name="code"
          label="验证码"
        >
          <Input
            suffix={
              <Button
                disabled={count !== 5}
                size="small"
                type="primary"
                onClick={() => getCode()}
              >
                {count === 5 ? "发送" : count + "s"}
              </Button>
            }
            placeholder="请输入短信验证码"
          />
        </Form.Item>
      </Form>
    </div>
  );
};
